# -*- coding: utf-8 -*-

from .. import util
import xml.dom.minidom as dom
import sys,traceback,cStringIO

# Stolen idea from wsgi.org
# All errors will be converted to xml text
class ExceptionCatcher:
	def __init__(self, app):
		self.app=app
	def __call__(self,environ,start_response):
		if environ.get('x-wsgiorg.throw_errors'):
			yield self.app(environ, start_response)
		else:
			try:
				output = ""
				for data in self.app(environ, start_response):
					yield data
				if(hasattr(self.app, 'xml')): self.xml = self.app.xml
			except SoftError:
				exc_info=sys.exc_info()
				status = '200 OK'
				headers = [('Content-type','text/xml')]
				if(not environ.has_key('renyare.errors')):
					start_response(status, headers, exc_info=exc_info)
					environ['renyare.errors'] = []
				environ['renyare.errors'].append(exc_info)
				out=cStringIO.StringIO()
				traceback.print_exc(file=out)
				out = util.xmlify(out.getvalue(), tag="error")
				self.xml = dom.parseString(out)
				yield out or ""

class ExceptionCollector:
	def __init__(self, app):
		self.app=app

	def __call__(self,environ,start_response):
		if environ.get('x-wsgiorg.throw_errors'):
			yield self.app(environ, start_response)
		else:
			try:
				output = ""
				for data in self.app(environ, start_response):
					yield data
				yield ""
			except:
				exc_info=sys.exc_info()
				instance = exc_info[0]
				status = '500 ServerError'
				headers = [('Content-type','text/plain')]
				if(not environ.has_key('renyare.errors')):
					start_response(status, headers, exc_info=exc_info)
					environ['renyare.errors'] = []
				out=cStringIO.StringIO()
				traceback.print_exc(file=out)
				out = util.xmlify(out.getvalue(), tag="error")
				yield out or ""

def error500(environ, start_response):
	"""Simplest possible application object"""
	status = '500 OMG'
	response_headers = [('Content-type','text/xml')]
	start_response(status, response_headers)
#    raise Error
	#return [util.xmlify('OMG! Error 500! Really sorry, guys!', 'error')]
	return ['OMG! Error 500! Really sorry, guys!']

def error404(environ, start_response):
    """"""
    status = '404 Not Found'
    response_headers = [('Content-type','text/xml')]
    start_response(status, response_headers)
    return [ util.xmlify('OMG! Error 404! Page NOT Found, mate!', 'error')]

class RenyareError(Exception):
	def __init__(self, msg):
		self._msg = msg

	def __repr__(self):
		return self._msg

	def __str__(self):
		return self._msg

	def output(self):
		status = "500 Oops"
		response_headers = [("content-type","text/plain")]
		self.start_response(status, response_headers, sys.exc_info())
		return True

class RenyareWarning(RenyareError):
	pass

__all__ = ['Error']
